#include "networkreply.h"
#include "qtimer.h"

void NetworkReply::setHttpStatusCode(int code, const QByteArray &statusText) {
	setAttribute(QNetworkRequest::HttpStatusCodeAttribute, code);
	if (statusText.isNull()) return;
	setAttribute(QNetworkRequest::HttpReasonPhraseAttribute, statusText);
}

void NetworkReply::setHeader(QNetworkRequest::KnownHeaders header, const QVariant &value) {
	QNetworkReply::setHeader(header, value);
}

void NetworkReply::setContentType(QString contentType) {
	setHeader(QNetworkRequest::ContentTypeHeader, contentType);
}

void NetworkReply::setContent(const QString &content) {
	setContent(content.toUtf8());
}

void NetworkReply::setContent(const QByteArray &content) {
	this->content = content;
	this->offset = 0;
	open(ReadOnly | Unbuffered);
	setHeader(QNetworkRequest::ContentLengthHeader, QVariant(content.size()));
	QTimer::singleShot(0, this, SIGNAL(readyRead()));
	QTimer::singleShot(0, this, SIGNAL(finished()));
}

void NetworkReply::abort() {}

qint64 NetworkReply::bytesAvailable() const {
	return this->content.size() - this->offset;
}

bool NetworkReply::isSequential() const {
	return true;
}

qint64 NetworkReply::readData(char *data, qint64 maxSize) {
	if (this->offset >= this->content.size()) return -1;
	qint64 number = qMin(maxSize, this->content.size() - this->offset);
	memcpy(data, this->content.constData() + this->offset, number);
	this->offset += number;
	return number;
}
